var redisDao = require("./redisDao.js")
var edition = require("./edition.js")
var httpHandler = require("./httpHandler.js")
const UPDATE_TIME = 10000
//数据采集
var model = function() {}

model.init = function(app) {
	this.app = app
	console.log("model init")
	redisDao.init(()=>{
		edition.init()
		this.app.edition = edition
		// setTimeout(this.update,3000)
		setInterval(this.update,UPDATE_TIME)
	})
}

model.update = function() {
	var list = edition.getEditions()
	var dateNow = Date.now()
	for(var i in list){
		if(!list[i].up_time || dateNow > list[i].up_time)
			model.syncEdition(i,list[i])
	}
}
//数据同步
model.syncEdition = function(name,editionInfo) {
	if(editionInfo.sync == 1){
		httpHandler.post(editionInfo.post,3001,"/daily_table",{pageSize:1,pageCurrent:1},function(data) {
			if(data && data.indexOf("<title>Error</title>") == -1){
				data = JSON.parse(data)
				for(var i = 0;i < data.list.length;i++){
					var str = (new Date(data.list[i]["date"])).toLocaleDateString()
					redisDao.db.hset("editionDay:"+name,str,JSON.stringify(data.list[i]))
				}
			}
		})
		httpHandler.post(editionInfo.post,3001,"/game_info",{},function(data) {
			if(!editionInfo.errorCount)
				editionInfo.errorCount = 0
			if(data && data.indexOf("<title>Error</title>") == -1){
				redisDao.db.hmset("editionTotal:"+name,JSON.parse(data))
				editionInfo.errorCount = 0
			}else{
				editionInfo.errorCount++
				if(editionInfo.errorCount >= 10)
					edition.pauseSync(name,function(){})
				console.log(name+" 同步失败 ",editionInfo.errorCount)
			}
			editionInfo.up_time = Date.now() + (Math.pow(editionInfo.errorCount,2) + 1) * UPDATE_TIME
		},function(error) {
			if(!editionInfo.errorCount)
				editionInfo.errorCount = 0
			editionInfo.errorCount++
			if(editionInfo.errorCount >= 10)
				edition.pauseSync(name,function(){})
			// console.log(name+" 同步失败 ",editionInfo.errorCount)
		})
	}
}
//数据初始化
model.initEdition = function(name,editionInfo) {
	if(editionInfo.sync == 1){
		httpHandler.post(editionInfo.post,3001,"/daily_table",{pageSize:1000,pageCurrent:1},function(data) {
			if(data){
				data = JSON.parse(data)
				for(var i = 0;i < data.list.length;i++){
					var str = (new Date(data.list[i]["date"])).toLocaleDateString()
					redisDao.db.hset("editionDay:"+name,str,JSON.stringify(data.list[i]))
				}
			}
		})
		httpHandler.post(editionInfo.post,3001,"/game_info",{},function(data) {
			if(data){
				redisDao.db.hmset("editionTotal:"+name,JSON.parse(data))
			}
		})
	}
}
module.exports = model